package br.edu.sistemaacademico;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.Document;

import br.edu.sistemaacademico.Decorator.ConcretDecorator;
import br.edu.sistemaacademico.adapter.IMenuCadastro;
import br.edu.sistemaacademico.observer.Observavel;
import br.edu.sistemaacademico.observer.Observer;
import br.edu.sistemaacademico.observer.ValidaEspecial;
import br.edu.sistemaacademico.observer.ValidaNumerosInteiros;
import br.edu.sistemaacademico.pojo.Disciplina;
import client.ClientCommand;

/**
 *
 * @author baron
 */
public class frmAtualizarDisciplina extends IMenuCadastro {

        ConcretDecorator cc = null;
        Disciplina disciplina = new Disciplina();
        Disciplina requisito;
        List<Disciplina> extra;
        public List<Object> campos = ClientCommand.getCampos("DisciplinaService");// new ArrayList<Object>();
        private List<Object> valores = new ArrayList<Object>();
        private List<Object> tamanho = new ArrayList<Object>();
        TabelaModelo tabModel;
        
    public frmAtualizarDisciplina(Disciplina disciplina) {
    	this.disciplina = disciplina;
    	execute();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jCheckBox1 = new javax.swing.JCheckBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        jLabel1.setText("Descricao");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText("Carga Horaria");
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField1.setName("jTextField1"); // NOI18N

        jTextField2.setName("jTextField2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        jCheckBox1.setText("Requisito");
        jCheckBox1.setName("jCheckBox1"); // NOI18N

        jButton1.setText("Cancelar");
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setText("Atualizar");
        jButton2.setName("jButton2"); // NOI18N

        jLabel3.setFont(new java.awt.Font("Dialog", 1, 9));
        jLabel3.setText("* Campo Obrigatorio");
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setFont(new java.awt.Font("Dialog", 1, 9));
        jLabel4.setText("* Campo Obrigatorio");
        jLabel4.setName("jLabel4"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCheckBox1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE)
                            .addComponent(jLabel3)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton1))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables

    private Observavel docDescricao = new Observavel();
    private Observavel docCargaHoraria = new Observavel();
 
    public void execute() {
         initComponents();
         tamanho.add("70");
         tabModel = new TabelaModelo(campos, tamanho, jTable1);
         ListSelectionModel listModel = jTable1.getSelectionModel();
         listModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
         listModel.addListSelectionListener(list);
         if (cc==null)
                cc = new ConcretDecorator(this);
          initObserver();
          //campoObrigatorio();
          addAcList();
          atualiza();
          populaFields(disciplina);
          cc.setVisible(true);
    }
    
    public void addAcList(){
    	ActionListener listener = new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(arg0.getSource().equals(jButton2))
					operacao();
				else
					cc.dispose();
			}
		};
		jButton2.addActionListener(listener);
		jButton1.addActionListener(listener);
		
    }
    
     public void initObserver(){
        Observer val = new ValidaEspecial();
        Observer numero = new ValidaNumerosInteiros();

          docDescricao.setDocument(jTextField1.getDocument());
          docCargaHoraria.setDocument(jTextField2.getDocument());

          docCargaHoraria.addObserver(numero);
          docDescricao.addObserver(val);

           jTextField1.getDocument().addDocumentListener(listener);
          jTextField2.getDocument().addDocumentListener(listener);
     }

      public void setTDescricao(Observavel observavel){
        observavel.setDocument(jTextField1.getDocument());
        observavel.setChanged();
        observavel.notifyObservers();
        jTextField1.setDocument(observavel.getDocument());
      }
    public void setTCargaHoraria(Observavel observavel){
        observavel.setDocument(jTextField2.getDocument());
        observavel.setChanged();
        observavel.notifyObservers();
        jTextField2.setDocument(observavel.getDocument());
    }

     public void getEventDocument(Document doc){
        if(doc.equals(docDescricao.getDocument()))
                setTDescricao(docDescricao);
        else if(doc.equals(docCargaHoraria.getDocument()))
                setTCargaHoraria(docCargaHoraria);
     }

      DocumentListener listener = new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
               getEventDocument(e.getDocument());
            }

            public void removeUpdate(DocumentEvent e) {
                getEventDocument(e.getDocument());
            }

            public void changedUpdate(DocumentEvent e) {
                 getEventDocument(e.getDocument());
            }
        };
        public void populaDisciplina(Disciplina o){
        	o.setNome(jTextField1.getText());
        	o.setCargaHoraria(Integer.parseInt(jTextField2.getText()));
        	if(requisito==null)
        		requisito = new Disciplina();
        	else if (requisito.getId()==null)
        		requisito.setId(0l);
        	else
        	o.setRequisito(requisito);
        }
        public void populaFields(Disciplina o){
        	jTextField1.setText(o.getNome());
        	jTextField2.setText(String.valueOf(o.getCargaHoraria()));
        /*	for(int i = 0; i < extra.size();i++ ){
        		if(extra.get(i).getId().equals(disciplina.getRequisito().getId()))
        		jTable1.setRowSelectionInterval(i,i);
        	}*/
        	
        	
        }
        public Disciplina getSelectedDisciplina(Long codigo){
        	return (Disciplina) ClientCommand.carregaObjeto("DisciplinaService", "codigo ="+codigo, "");
    	}
        ListSelectionListener list = new ListSelectionListener() {
    		
    		@Override
    		public void valueChanged(ListSelectionEvent e) {
    			try{
    				if(jTable1.getSelectedRow()>=0){
    			 requisito = getSelectedDisciplina(Long.parseLong(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()));
    				}
    				}catch(ArrayIndexOutOfBoundsException ea){
    				requisito = null;
    			}
    		}
    	};	
    	 public void atualiza(){
    	    	((DefaultTableModel) jTable1.getModel()).setNumRows(0);
    	    	jTable1.updateUI();
    	    	extra = (List)ClientCommand.carregar("DisciplinaService","codigo = codigo", "");
    	    	for(int i = 0; i < extra.size();i++ ){
    	    		if(extra.get(i).getId()==disciplina.getId()) 
    	    			if(i!=extra.size()-1)
    	    				continue;
    	    				else
            	    		return;
    	    			else if(extra.get(i).getRequisito().getId()==disciplina.getId())
    	    		if(i!=extra.size()-1)
    	    			continue;
    	    			else
        	    		return;
    	    		valores = new LinkedList<Object>();
    	    		valores.add(extra.get(i).getId());
    	    		valores.add(extra.get(i).getNome());
    	    		if(extra.get(i).getRequisito().getId()==0)
    	    			valores.add("Nenhum");
					else{
						extra.get(i).setRequisito((Disciplina) ClientCommand.carregaObjeto("DisciplinaService","codigo = "+extra.get(i).getRequisito().getId(), ""));
						valores.add(extra.get(i).getRequisito().getNome());
					}
    	    		//valores.add(extra.get(i).getRequisito().getId());
    	    		valores.add(extra.get(i).getCargaHoraria());
    	     		tabModel.setValores(valores);
    	     		if(extra.get(i).getId().equals(disciplina.getRequisito().getId()))
    	        		jTable1.setRowSelectionInterval(jTable1.getRowCount()-1,jTable1.getRowCount()-1);
    	     		
    	    		valores.clear();
    	    	}
    	    }
      	
    	 public void limpaFields(){
        	 jTextField1.setText("");
        	 jTextField2.setText("");
        }

        
    	@Override
    	public void menuExemplo(JMenuItem item) {
    		// TODO Auto-generated method stub
    		
    	}

    	@Override
    	public void menuFechar(JMenuItem item) {
    		cc.dispose();		
    	}

    	@Override
    	public void menuLimpa(JMenuItem item) {
    		limpaFields();		
    	}

    	@Override
    	public void menuManual(JMenuItem item) {
    		// TODO Auto-generated method stub		
    	}

    	@Override
    	public void menuMementor(JMenuItem item) {
    		// TODO Auto-generated method stub		
    	}

    	@Override
    	public void menuOperacao(JMenuItem item) {
    		item.setText("Atualizar Disciplina");
    		operacao();
    		limpaFields();
    	}

    	@Override
    	public void menuSobre(JMenuItem item) {
    		// TODO Auto-generated method stub
    		
    	}
    	public void operacao(){
			populaDisciplina(disciplina);
			ClientCommand.alterar("DisciplinaService",disciplina);
			JOptionPane.showMessageDialog(null, "Disciplina Atualizada com sucesso");

    	}
}
